package com.servlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        String uri = request.getRequestURI();


        if(uri.equals("/")||uri.contains("jsp")&&!uri.endsWith("login.jsp")&&!uri.endsWith("login1.jsp")||uri.contains("Servlet")&&!uri.endsWith("login")&&!uri.endsWith("logout")&&!uri.endsWith("login1")&&!uri.endsWith("logout1")){
            if(request.getSession().getAttribute("user")!=null||request.getSession().getAttribute("owner")!=null){
                chain.doFilter(req,resp);
            }else{
                request.setAttribute("errMsg", "您还没有登录");
                request.getRequestDispatcher("/login.jsp").forward(req,resp);
            }
        }else{
            chain.doFilter(req,resp);
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
